﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using t_TestingLibrary;
using HTMLTablePageScanner;
using System.ComponentModel.Composition;
using System.IO;
using RenderEngineInterfaces;
using DeepZoomPivotConstructor.VisualLib;
using DeepZoomPivotConstructor.PivotLib;
using PaperRenderingInterfaces;
using System.Drawing;
using System.Diagnostics;

namespace t_HTMLTablePageScanner
{
    [TestClass]
    public class t_WebTableCellScanner
    {
        [TestInitialize]
        public void TestSetup()
        {
            Utilities.MyClassInit();
        }

        [TestCleanup]
        public void TestCleanup()
        {
            Utilities.MyClassDone();
        }

        [TestMethod]
        public void TestCtor()
        {
            WebTableCellScanner scanner = new WebTableCellScanner(); 
        }

        /// <summary>
        /// Load a file instead of accessing the web.
        /// </summary>
        [Export(typeof(IWebAccess))]
        private class LoadAFile : IWebAccess
        {
            public FileInfo theFileToLoad;
            public string UrlAskedFor { get; set; }

            public string GetUriAsString(Uri whatToLoad)
            {
                UrlAskedFor = whatToLoad.OriginalString;

                return LoadFile(theFileToLoad);
            }

            /// <summary>
            /// Load up the req' file.
            /// </summary>
            /// <param name="finfo"></param>
            /// <returns></returns>
            private string LoadFile(FileInfo finfo)
            {
                if (finfo.Exists)
                {
                    using (var reader = finfo.OpenText())
                    {
                        return reader.ReadToEnd();
                    }
                }
                else
                {
                    return null;
                }
            }


            public DateTime? GetLastModificationTime(Uri whatToCheck)
            {
                return DateTime.Now;
            }
        }

        [Export(typeof(IRenderEngine))]
        class RenderEngineDummy : IRenderEngine
        {
            public System.Threading.Tasks.Task<DeepZoomPivotConstructor.VisualLib.Visual> RenderToFuture(object what, Type[] disallowRenderPlugins = null, bool forceAsComposableUnit = false)
            {
                throw new NotImplementedException();
            }

            public DeepZoomPivotConstructor.VisualLib.Visual Render(object what, Type[] disallowRenderPlugins = null, bool forceAsComposableUnit = false)
            {
                Visual v = new VisualBitmapImage(1.0, 1.0, 100, Color.Black);
                v.SetAsComposableUnit(null);
                Trace.WriteLine("Rendering " + what.ToString());
                return v;
            }
        }

        [TestMethod]
        public void TestDZEROWebPage()
        {
            WebTableCellScanner target = new WebTableCellScanner();
            var laf = new LoadAFile() { theFileToLoad = new FileInfo("..\\..\\..\\t_HTMLTablePageScanner\\T80.html") };
            Utilities.AddPart(laf);
            Utilities.AddPart(new RenderEngineDummy());
            Utilities.Compose(target);

            var result = target.Render("http://www-d0.fnal.gov/Run2Physics/WWW/results/prelim/TOP/T80/");
            var results = result.ToArray();

            Assert.AreEqual(10, results.Count(), "Wrong number of pictures were picked up!");
            PivotImage pi = results.First();

            Assert.AreEqual("jpeg", pi.Name, "Name of image is not right");

            Assert.IsTrue(pi.Count() > 0, "Expected some meta data with the image");

            Assert.AreEqual(2, FindMetadata<PivotMetadataURL>(pi, "Graphics Files").Count(), "Expecting 2 links for the first image");

            Assert.AreEqual(1, FindMetadata<PivotMetadataURL>(pi, "More Information").Count(), "Expecting 1 links to more information");

            Assert.AreEqual(1, FindMetadata<PivotMetadataDateTime>(pi, "Date").Count(), "There should been a date!");

            Assert.IsNotNull(pi.Image, "Image of first image should not be null!");
            Assert.IsTrue(pi.Image.IsCompositionUnit, "And the image should be a composable unit!");
        }

        [TestMethod]
        public void TestCombinedHiggsPage()
        {
            WebTableCellScanner target = new WebTableCellScanner();
            var laf = new LoadAFile() { theFileToLoad = new FileInfo("..\\..\\..\\t_HTMLTablePageScanner\\combinedHiggs.html") };
            Utilities.AddPart(laf);
            Utilities.AddPart(new RenderEngineDummy());
            Utilities.Compose(target);

            var result = target.Render("http://tevnphwg.fnal.gov/results/SM_Higgs_Fall_07/");
            var results = result.ToArray();

            Assert.AreEqual(6, results.Count(), "Wrong number of pictures were picked up!");
        }

        /// <summary>
        /// Hunt throught the metadata!
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <param name="pmf"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        private T1[] FindMetadata<T1>(PivotImage pmf, string p)
            where T1 : PivotMetadataBase
        {
            var md = from m in pmf
                     where m.Name == p && m.GetType() == typeof(T1)
                     let masType = (T1)m
                     where masType != null
                     select masType;
            return md.ToArray();
        }
    }
}
